import sys
import subprocess
import psutil
from PySide6.QtWidgets import (
    QApplication,
    QMainWindow,
    QWidget,
    QVBoxLayout,
    QPlainTextEdit,
    QSplitter,
    QPushButton,
    QHBoxLayout,
)
from PySide6.QtGui import QGuiApplication, QScreen
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtCore import QUrl, QProcess, QIODevice, Qt


class WebViewApp(QMainWindow):
    def __init__(self):
        super().__init__()

        # 设置窗口
        self.setWindowTitle("网页浏览器")
        self.setGeometry(100, 100, 1200, 768)

        # 创建主布局
        self.main_widget = QWidget()
        self.setCentralWidget(self.main_widget)
        self.layout = QVBoxLayout()
        self.main_widget.setLayout(self.layout)

        # 创建可调整大小的分隔布局
        self.splitter = QSplitter(Qt.Vertical)
        self.layout.addWidget(self.splitter)

        # 创建WebView
        self.browser = QWebEngineView()
        self.splitter.addWidget(self.browser)

        # 创建控制台输出区域
        self.console_output = QPlainTextEdit()
        self.console_output.setReadOnly(True)
        self.splitter.addWidget(self.console_output)

        # 设置初始大小比例
        self.splitter.setSizes([600, 200])

        # 添加清除按钮
        self.clear_button = QPushButton("清除控制台")
        self.clear_button.clicked.connect(self.console_output.clear)
        self.clear_button.setFixedSize(
            self.clear_button.sizeHint().width() + 20,
            self.clear_button.sizeHint().height() + 20,
        )
        self.clear_button.setStyleSheet("color: rgb(25, 118, 210);")

        # 创建底部布局
        self.bottom_layout = QHBoxLayout()
        self.bottom_layout.addStretch()
        self.bottom_layout.addWidget(self.clear_button)
        self.bottom_layout.addStretch()

        # 将底部布局添加到主布局
        self.layout.addLayout(self.bottom_layout)

        # 加载网页
        self.load_webpage()

        # 执行外部应用程序
        self.run_external_app()

    def run_external_app(self):
        """运行外部应用程序并捕获输出"""
        try:
            # 检查进程是否已运行
            process_name = "JiJiDownCore-win64.exe"
            is_running = any(
                p.info["name"] == process_name for p in psutil.process_iter(["name"])
            )

            if not is_running:
                # 创建 QProcess 对象
                self.process = QProcess()
                self.process.setProgram(
                    "X:\\Program Files\\JiJiDown\\resources\\JiJiDownCore-win64.exe"
                )
                self.process.setArguments(["-debug"])
                self.process.setWorkingDirectory(
                    "X:\\Program Files\\JiJiDown\\resources"
                )

                # 捕获标准输出和错误输出
                self.process.readyReadStandardOutput.connect(self.handle_stdout)
                self.process.readyReadStandardError.connect(self.handle_stderr)

                # 启动进程
                self.process.start()
                self.console_output.appendPlainText("已启动外部程序")
            else:
                self.console_output.appendPlainText("程序已在运行，跳过启动")
        except Exception as e:
            self.console_output.appendPlainText(f"操作失败: {e}")

    def handle_stdout(self):
        """处理标准输出"""
        data = self.process.readAllStandardOutput().data().decode("utf-8")
        self.console_output.appendPlainText(data)

    def handle_stderr(self):
        """处理错误输出"""
        data = self.process.readAllStandardError().data().decode("utf-8")
        self.console_output.appendPlainText(data)

    def load_webpage(self):
        """加载网页"""
        self.browser.setUrl(QUrl("https://beta.sabe.cc/"))


import os

os.environ["QT_LOGGING_RULES"] = "qt.qpa.*=false"  # 禁用部分无关日志

from PySide6.QtCore import qInstallMessageHandler


def ignore_painter_warnings(msg_type, context, message):
    if "QPainter::" not in message:
        pass  # 完全静默，或选择性地打印其他消息


qInstallMessageHandler(ignore_painter_warnings)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = WebViewApp()
    window.show()
    sys.exit(app.exec())
